// 键盘移动
function processKeyPress(evt) {
    var leftArrow = 37;
    var upArrow = 38;
    var rightArrow = 39;
    var downArrow = 40;
    var panRate = 10;
    switch (evt.keyCode) {
        case leftArrow:
            move(panRate, 0, 1);
            break;
        case rightArrow:
            move(-panRate, 0, 1);
            break;
        case upArrow:
            move(0, panRate, 1);
            break;
        case downArrow:
            move(0, -panRate, 1);  
            break;                         
    }
};

// 滚轮缩放
function zoom(zoomType) {
    var zoomRate = 1.1;
    if (zoomType == 'zoomIn') {
        move(0, 0, 1/zoomRate); 
    } else if (zoomType == 'zoomOut') {
        move(0, 0, zoomRate); 
    }  
};
    
function zoomViaMouseWheel(mouseWheelEvent) {
    var zoomRate = 1.1;   
    if (mouseWheelEvent.wheelDelta > 0) {
        // zoom('zoomIn');
        move(0, 0, 1/zoomRate); 
    } else {
        // zoom('zoomOut');
        move(0, 0, zoomRate); 
    }
    mouseWheelEvent.cancelBubble = true;  
    return false;             
};

// 鼠标拖动
function drag() {
    var startX=event.x;
    var startY=event.y;
    var deltaX;
    var deltaY;
    document.removeEventListener("mouseup",upHandler,true);
    document.removeEventListener("mousemove",moveHandler,true);
    if(document.addEventListener) {
        document.addEventListener("mousemove",moveHandler,true);
        document.addEventListener("mouseup",upHandler,true);
    }
    function moveHandler() {
        deltaX = startX - event.x;
        deltaY = startY - event.y;
    }
    function upHandler() {
        move(deltaX, deltaY);
        document.removeEventListener("mouseup",upHandler,true);
        document.removeEventListener("mousemove",moveHandler,true);
    }
};

// 移动图片
function move(x, y, rate) {
    var theSvgElement = document.getElementById('svgProcess');
    var viewBox = theSvgElement.getAttribute('viewBox');
    var viewBoxValues = viewBox.split(' ');
    if (isNaN(x)) {
        x = 0;
    }
    if (isNaN(y)) {
        y = 0;
    }
    if (isNaN(rate)) {
        rate = 1;
    }
    viewBoxValues[0] = parseFloat(viewBoxValues[0]) + x;
    viewBoxValues[1] = parseFloat(viewBoxValues[1]) + y;
    viewBoxValues[2] = parseFloat(viewBoxValues[2]) * rate;
    viewBoxValues[3] = parseFloat(viewBoxValues[3]) * rate;
    theSvgElement.setAttribute('viewBox', viewBoxValues.join(' ')); 
};

// 初始化
function initialize() {        
    window.addEventListener('keydown', processKeyPress, true); 
    window.addEventListener('mousewheel', zoomViaMouseWheel, true); 
    window.addEventListener('mousedown', drag, true);
};

// 设置默认viewBox
function setViewBox(viewBox) {
    viewBoxFinal = viewBox;
};

